﻿@inherits BootstrapInputBase<string>

<AutoFill TValue="SelectedItem" Value="CurrnetItem"
          OnGetDisplayText="OnGetDisplayText" IsLikeMatch="true"
          OnSelectedItemChanged="OnSelectedItemChanged"
          OnCustomFilter="OnCustomFilter"
          Items="Items">
    <Template>
        <div class="d-flex">
            <div class="ps-2">
                <div>@context.Text</div>
                <div class="bb-sub">@context.Value</div>
            </div>
        </div>
    </Template>
</AutoFill>

@code {

    SelectedItem CurrnetItem { get; set; }

    List<SelectedItem> Items { get; set; }

    [Parameter]
    public string SelectedValue { get; set; }

    [Parameter]
    public EventCallback<string> SelectedValueChanged { get; set; }

    async Task OnSelectedItemChanged(SelectedItem item)
    {
        await SelectedValueChanged.InvokeAsync(item.Value);
    }

    protected override void OnParametersSet()
    {
        if (Items.Any(x => x.Value == SelectedValue))
        {
            CurrnetItem = Items.Single(x => x.Value == SelectedValue);
        }
    }

    protected override void OnInitialized()
    {
        Items = new List<SelectedItem>()
            {
                new SelectedItem("","全部"),
                new SelectedItem("CN","中国(China)"),
                new SelectedItem("US","美国(American)")
            };
    }

    string OnGetDisplayText(SelectedItem item)
    {
        return item.Value;
    }

    Task<IEnumerable<SelectedItem>> OnCustomFilter(string text)
    {
        if (!string.IsNullOrEmpty(text))
        {
            return Task.FromResult(Items.Where(x => x.Value.StartsWith(text) || x.Text.Contains(text)));
        }
        return Task.FromResult(Items.AsEnumerable());
    }

    public void Update()
    {
        StateHasChanged();
    }
}
